package de.zainodis.triplog.data;

import android.content.Context;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by fzarrai on 10/4/2014.
 */
public class DataProvider {

    private static TripEntry currentTrip;

    /**
     * Ends all ongoing trips. Only use this, if you intend to start a new trip.
     * Make sure to call this method from a background thread since it involves database queries.
     */
    public static void endAllOngoingTrips(Context context) {

        //First check if we have a cached trip, if yes end that one and save the changes
        if (currentTrip != null) {
            currentTrip.createOrUpdate(context);
        }
        TripEntry.closeOngoingTrips(context);
    }

    /**
     * Adds the given note to the current trip. This will also set the foreign key on the entry.
     *
     * @param entry new entry to add.
     */
    public static void addNote(DiaryEntry entry) {
        if (entry != null && currentTrip != null) {
            entry.setFkTripEntry(currentTrip.getId());
        }
        List<DiaryEntry> entries = getNotes();
        entries.add(entry);
        updateNotes(entries);
    }

    public static void updateNotes(List<DiaryEntry> notes) {
        currentTrip.setDiaryEntries(notes);
    }

    public static List<DiaryEntry> getNotes() {
        if (currentTrip == null) {
            return new ArrayList<DiaryEntry>();
        }

        return currentTrip.getDiaryEntries();
    }

    public static TripEntry getCurrentTrip() {
        return currentTrip;
    }

    /**
     * @return true if the current trip is ongoing;false otherwise or if there currently is no trip.
     */
    public boolean isOngoingTrip() {
        return currentTrip != null && !currentTrip.hasEndDate();
    }

    public static void setCurrentTrip(TripEntry trip) {
        currentTrip = trip;
    }

    public static void clearAll() {
        currentTrip = null;
    }

    /**
     * This will not query the database for ongoing trips!
     *
     * @return true if there is a cached, ongoing trip; false otherwise.
     */
    public static boolean hasOngoingTrip() {
        return currentTrip != null;
    }

    public static boolean hasLocation() {
        return hasOngoingTrip() && currentTrip.getLocation() != null;
    }
}
